package org.aom.service.security.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;

import com.octo.captcha.service.CaptchaService;

/**
 * 
 * @author Saya Yang
 * 用于Capthca以及SpringSecurity2.0认证的bean，由于jsf自身限制暂时只能以这种方式进行限制，这是采取的让步之道。
 *
 */
@Service
public class AuthenticationService {

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private CaptchaService captchaService;
	
	public CaptchaService getCaptchaService() {
		return captchaService;
	}

	public void loginAuthenticate(String j_username,String j_password) throws BadCredentialsException {
		UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(
				j_username, j_password);
		Authentication auth = authenticationManager
				.authenticate(authReq);
		if (auth.isAuthenticated() == true) {
			SecurityContext secCtx = SecurityContextHolder
					.getContext();
			secCtx.setAuthentication(auth);
		}

	}

	public Boolean captchaAuthenticate(String sessionid,String j_captcha) {
		return captchaService.validateResponseForID(sessionid, j_captcha);
	}

}
